var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cors = require('cors')
var { skuProductListModel } = require("./model/product") 
const PubSub = require('pubsub-js'); 

const indexRouter = require('./routes/index');
const userRouter = require('./routes/user');
const cartRouter = require('./routes/cart')
const homeRouter = require('./routes/home')
const orderRouter = require('./routes/order') 
const cateRouter = require('./routes/cate')
const seckillRouter = require('./routes/seckill')

var app = express();
app.use(cors())

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');


app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/user', userRouter);
app.use('/cart', cartRouter);
app.use('/home', homeRouter);
app.use('/order', orderRouter);
app.use('/activity/seckill', seckillRouter);
app.use('/cate', cateRouter);

app.get('/', (req, res) => {
  res.send('Welcome to the backend server!');
});

// 发布模式
function checkCategoryChanges() {
  // 检查分类数据是否发生了变化
  // 如果发生了变化，将其发布到 'categoryChange' 事件中
  // categories.push('New Category'); // 这里只是一个示例
  PubSub.publish('categoryChange', "categories");
}

// 设置定时器，每5秒检查一次分类数据变化
setInterval(checkCategoryChanges, 5000);
// PubSub.publish('message', "message");
// app.use(async function (req, res, next) {
//   let list = await skuProductListModel.find()
//   let oldList = JSON.parse(localStorage.getItem("productList") || "[]")
//   let flag = _.isEqual(list, oldList)
//   // if (!flag) {
//     PubSub.publish('handlerAgin', 'cateList')
//   // }
//   next();
// });

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
